﻿using Microsoft.WindowsAPICodePack.Dialogs;
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Telerik.Windows.Controls;
using TruckScale.Helpers;
using TruckScale.Models;
using static TruckScale.Helpers.LogHelper;

namespace TruckScale.ViewModels
{
  public class DBBackupViewModel : ViewModelBase
  {

    public string Theme { get; set; } = Global._weighConfig["Theme"];
    public string MainFontSize { get; set; } = Global._weighConfig["MainFontSize"];
    public string InfoBar { get; set; }
    public string BackupPath { get; set; }
    private string _autoBackupFrequency;
    public string AutoBackupFrequency
    {
      get => _autoBackupFrequency;
      set
      {
        if (value != _autoBackupFrequency)
        {
          _autoBackupFrequency = value;
          Global._weighConfig["AutoBackupFrequency"] = AutoBackupFrequency = value;
          WeighConfigModel.UpdateConfig("AutoBackupFrequency", value);
        }
      }
    }
    public DelegateCommand LoadPathCommand { get; private set; }
    public DelegateCommand BackupCommand { get; private set; }
    //public DelegateCommand AutoBackupCommand { get; private set; }
    public DBBackupViewModel()
    {
      BackupPath = Global._weighConfig["BackupPath"];
      _autoBackupFrequency = Global._weighConfig["AutoBackupFrequency"];
      LoadPathCommand = new DelegateCommand(OnLoadPathExecuted);
      BackupCommand = new DelegateCommand(OnBackupExecuted);
    }

    private void OnLoadPathExecuted(object obj)
    {
      CommonOpenFileDialog dialog = new CommonOpenFileDialog
      {
        InitialDirectory = BackupPath,
        IsFolderPicker = true
      };
      if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
      {
        Global._weighConfig["BackupPath"] = BackupPath = dialog.FileName;
        WeighConfigModel.UpdateConfig("BackupPath", BackupPath.Replace(@"\", @"\\"));
      }
    }

    private void OnBackupExecuted(object obj)
    {
      try
      {
        InfoBar = "正在备份...";

        string cnnstr = ConfigurationManager.ConnectionStrings["mysql"].ConnectionString;
        string fileName = Path.Combine(BackupPath, DateTime.Now.ToString("yyyyMMddHHmmss") + ".sql");
        var cnnDictionary = DBHelper.ParseConnectionString(cnnstr);

        string command = $@"mysqldump -h {cnnDictionary["Data Source"]} -P {cnnDictionary["port"]} -u {cnnDictionary["userid"]} -p{cnnDictionary["password"]} --column-statistics=0 {cnnDictionary["initial catalog"]} > ""{fileName}""";

        SetLog($"执行备份命令：{command}", LogType.OperationLogger, LogLevel.Debug);

        // 执行备份命令
        ExecuteCommand(command);

        InfoBar = "备份成功: " + fileName;
      }
      catch (Exception ex)
      {
        InfoBar = "备份失败，请查看操作日志";
        SetLog($"备份失败：{ex.Message}", LogType.OperationLogger, LogLevel.Error);
      }
    }

    // 执行命令行命令
    static void ExecuteCommand(string command)
    {
      ProcessStartInfo processInfo = new ProcessStartInfo
      {
        FileName = "cmd.exe",
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        RedirectStandardError = true, // 捕获错误输出
        UseShellExecute = false,
        CreateNoWindow = true
      };

      Process process = new Process
      {
        StartInfo = processInfo
      };
      process.Start();

      process.StandardInput.WriteLine(command);
      process.StandardInput.Flush();
      process.StandardInput.Close();

      // 读取标准输出并打印
      string output = process.StandardOutput.ReadToEnd();
      Console.WriteLine(output);

      // 读取标准错误并打印（如果有错误的话）
      string errorOutput = process.StandardError.ReadToEnd();
      if (!string.IsNullOrEmpty(errorOutput))
      {
        Console.WriteLine(errorOutput);
      }

      process.WaitForExit();
    }

    public void ExecuteAutoBackup()
    {
      Task.Run(() =>
      { // 计算时间差（天数）
        TimeSpan ts = DateTime.Now - DateTime.Parse(Global._weighConfig["LastBackupTime"]);
        int daysDifference = ts.Days;

        // 判断不同的备份频率
        if ((AutoBackupFrequency == "3" && daysDifference >= 30) ||
            (AutoBackupFrequency == "2" && daysDifference >= 7) ||
            (AutoBackupFrequency == "1" && daysDifference >= 1))
        {
          OnBackupExecuted(null);
          WeighConfigModel.UpdateConfig("LastBackupTime", DateTime.Now.ToString());
          SetLog("自动备份完成", LogType.OperationLogger);
        }

      });
    }
  }
}
